import axios from 'axios'

const apiClient = axios.create({
  // 不需要写前面的 http://ip:port
  baseURL: '/api',
  timeout: 5000
})

apiClient.interceptors.request.use(
  config => {
    if (config.url === '/auth/login' || config.url === '/auth/logout' || config.url === '/user/register') {
      return config
    }
    // 其他请求需要携带token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

apiClient.interceptors.response.use(
  (response) => {
    return response.data
  },
  error => {
    return Promise.reject(error.request)
  }
)

export default apiClient
